package cn.fzm.controller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Dremeue
 * @create 2019-10-07 18:11
 **/
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/fileupload")
    public String fileupload(HttpServletRequest request, MultipartFile upload) throws IOException {
        System.out.println("SpringMVC方式的文件上传...");

        // 先获取要上传的文件目录
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        // 创建File对象, 向该路径上传文件
        File file = new File(path);
        // 判断路径是否存在
        if (!file.exists()) {
            file.mkdirs();
        }

        // 获取上传的文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件名称唯一化
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;

        // 上传文件
        upload.transferTo(new File(file, filename));

        return "success";
    }

    @RequestMapping("/fileupload2")
    public String fileupload2(MultipartFile upload) throws IOException {
        System.out.println("SpringMVC跨服务器方式的文件上传...");

        // 定义图片服务器的请求路径
        String path = "http://localhost:9090/uploads/";

        // 获取上传的文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件名称唯一化
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;

        // 创建客户端
        Client client = Client.create();

        // 连接图片服务器
        WebResource webResource = client.resource(path + filename);

        // 上传文件
        webResource.put(upload.getBytes());

        return "success";
    }
}
